const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
	$U_SetItem,
	$U_GetItem,
} = require('@utils/storage')
const {
	setFormEdit,
	setBtnEdit,
} = require('./api-utils');

/**
 * 初始化项目数据
 * @param  {[type]} apiComp   [description]
 * @param  {[type]} projectId [description]
 * @return {[type]}           [description]
 */
async function loadProjectData(apiComp, projectId, options) {
	let userInfo = $U_UserInfo()
	let version = ''
	let project_data = ''
	let isLock = false
	let tmpApiDetail = null;
	let testServerUrl = '';
	let projectName = '';
	let editProjectData = null
	let orgProjectData = null
	let history = {
		// 接口操作记录
		apis: {},
		// 模块操作记录
		modules: {},
	}
	if (options && options.project_data) {
		// 加载各版本数据
		version = apiComp.store && apiComp.store.version || ''
		project_data = options.project_data
		orgProjectData = getOrgProjectDataJSON(project_data)
	} else if (options && options.tmpEditProjectData && options.tmpHistory && options.tmpCurrentCheckApi) {
		// 加载非正常退出未保存数据
		editProjectData = options.tmpEditProjectData
		history = options.tmpHistory
		tmpApiDetail = options.tmpCurrentCheckApi
		orgProjectData = apiComp.store.orgProjectData
		isLock = true
	} else {
		// 接口加载最新版本数据
		let project_result = await reqGet('/ult/api', {
			project_id: projectId,
		})
		let {
			id,
			name,
			is_locked,
			locked_user,
			test_server_url,
		} = project_result;
		projectName = name
		testServerUrl = test_server_url
		tmpApiDetail = apiComp.store && apiComp.store._currentCheckApiDetail || null
		project_data = project_result.project_data || ''
		version = project_result.version
		isLock = locked_user.indexOf(userInfo.realname) > -1 && is_locked == 1 || false
		orgProjectData = getOrgProjectDataJSON(project_data)
	}
	console.log('orgProjectData', orgProjectData)
	if (!orgProjectData || !orgProjectData.treeData || !orgProjectData.apis || !orgProjectData.modules) {
		apiComp.btnEdit.linkbutton('disable')
		apiComp.btnVersion.linkbutton('disable')
		$.messager.alert({
			title: '提示',
			msg: '参数加载错误！'
		})
		return false
	}
	testServerUrl = orgProjectData.testServerUrl = testServerUrl || orgProjectData.testServerUrl
	orgProjectData = orgProjectData || $.extend(true, {}, orgProjectData)
	editProjectData = editProjectData || $.extend(true, {}, orgProjectData)
	apiComp.store = {
		version,
		projectId,
		projectName,
		// 原始项目数据
		orgProjectData,
		// 编辑项目数据
		editProjectData,
		// 项目锁定
		isLock,
		// 是否可以保存
		isSave: true,
		isTest: false,
		// 修改历史记录
		history,
		// 是否记录历史，处理加载详情数据变更时问题
		record: false,
		// 测试返回值
		tmpTestResponse: null,
		isHistoryVersion: false,
		_currentTreeNode: null,
		// 当前正在编辑的api信息(编辑状态)
		_currentEditApiDetail: null,
		// 当前选中的api信息
		_currentCheckApiDetail: null,
		_$modify: {},
		// req请求参数，res响应参数
		_flag: '',
		// 当前接口请求参数相关信息
		reqCurrent: {
			orgParameterList: null,
			editRow: null,
			parentRow: null,
			// 测试请求值对应参数
			editValueRow: null,
		},
		// 当前接口响应参数相关信息
		resCurrent: {
			orgParameterList: null,
			editRow: null,
			parentRow: null,
		},
	};
	// 初始化接口目录树
	let firstApiId = 'api-00000000'
	apiComp.store._currentCheckApiDetail = tmpApiDetail || orgProjectData.apis[firstApiId]
	apiComp.treeComp.tree('loadData', orgProjectData.treeData)
	openModule(apiComp)
	apiComp.testServerUrlComp.textbox('setValue', testServerUrl)
	loadAPIDetail(apiComp)
	setBtnEdit(apiComp)
	setFormEdit(apiComp)
	return apiComp
}

function openModule(apiComp) {
	let {
		store,
		treeComp,
	} = apiComp
	let id = store._currentCheckApiDetail.id
	let node = treeComp.tree('find', id)
	let parentNode = treeComp.tree('getParent', node.target)
	while (parentNode) {
		treeComp.tree('expand', parentNode.target)
		parentNode = treeComp.tree('getParent', parentNode.target)
	}
}

/**
 * 加载接口详情信息
 * @param  {[type]} apiComp [description]
 * @param  {[type]} detail  [description]
 * @return {[type]}         [description]
 */
function loadAPIDetail(apiComp) {
	let {
		store,
		formComp,
		treeComp,
		reqParamsComp,
		resParamsComp,
	} = apiComp;
	let node = store._currentCheckApiDetail;
	if (!node || !node.id) {
		store._currentEditApiDetail = null;
		store._currentTreeNode = null;
		formComp.form('load', {
			id: '',
			name: '',
			contentType: '',
			path: '',
			method: '',
			intro: '',
		})
		return false
	}
	let currentRequset = store.currentRequset;
	let currentResponse = store.currentResponse;
	let editProjectData = store.editProjectData;
	// api信息，从editProjectData中获取
	// 处理有模块变为接口的节点
	let detail = editProjectData.apis[node.id] = editProjectData.apis[node.id] || {
		id: node.id,
		name: '',
		contentType: '',
		path: '',
		method: '',
		intro: '',
		requestParameterList: [],
		responseParameterList: [],
	};
	// 当前编辑接口详情
	if (store.isLock)
		store._currentEditApiDetail = detail;
	else
		store._currentEditApiDetail = null;
	// 接口测试时使用的临时结果
	store.tmpResult = null
	let {
		id,
		name,
		contentType,
		path,
		method,
		intro,
		requestParameterList,
		responseParameterList,
	} = detail;
	// 加载详情信息时不记录变更历史
	store.record = false
	store.tmpTestResponse = null
	formComp.form('load', {
		id,
		name,
		contentType,
		path,
		method,
		intro,
	})
	try {
		requestParameterList = Array.isArray(requestParameterList) ? requestParameterList : JSON.parse(requestParameterList)
		responseParameterList = Array.isArray(responseParameterList) ? responseParameterList : JSON.parse(responseParameterList)
	} catch (e) {
		console.log('detail parameter json parse error ==> ', name, id, e)
		console.log('requestParameterList', requestParameterList)
		console.log('responseParameterList', responseParameterList)
		requestParameterList = []
		responseParameterList = []
	}
	reqParamsComp.treegrid('loadData', requestParameterList)
	resParamsComp.treegrid('loadData', responseParameterList)
	node = treeComp.tree('find', id)
	treeComp.tree('select', node.target)
}

module.exports = {

	loadProjectData,

	loadAPIDetail,

}

/**
 * 解析接口JSON格式数据
 * @param  {[type]} project_data [description]
 * @return {[type]}              [description]
 */
function getOrgProjectDataJSON(project_data) {
	let projectDataJSON = null
	project_data = project_data.replace(/^["'`]|["'`]$/g, '')
	try {
		projectDataJSON = JSON.parse(project_data)
	} catch (e) {
		try {
			projectDataJSON = new Function(`return ${project_data};`)()
		} catch (e) {
			projectDataJSON = null
		}
		console.log('e', e)
		console.log('project_data', project_data)
	}
	return projectDataJSON
}